<template>
  <div class="content">
    <!-- 存在不合格内容时展示 -->
    <div class="content-table" v-if="isError">
      <div class="divider">整改反馈:</div>
      <el-table :data="filterFormData(formData.insContentList)" border>
        <!-- :span-method="objectSpanMethod" -->
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column prop="content" label="检查内容"></el-table-column>
        <el-table-column prop="requests" label="标准要求"> </el-table-column>
        <el-table-column prop="insMethod" label="检查方法">
          <template #default="{ row }">
            <el-input disabled v-model="row.insMethod"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="insSummary" label="检查小结">
          <template #default="{ row }">
            <el-input disabled v-model="row.insSummary"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="是否合格" width="180">
          <template #default="{ row }">
            <el-radio-group v-model="row.isQualifiedCheck">
              <el-radio disabled label="1">合格</el-radio>
              <el-radio disabled label="0">不合格</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column label="附件">
          <template #default="{ row }">
            <template v-if="row.insContentAttachmentArr.length">
              <div
                v-for="item in row.insContentAttachmentArr"
                :key="item?.uuidFile"
              >
                <div class="file-item">
                  <div class="file-item--left" :title="item.fileName">
                    <i class="el-icon-folder"></i>{{ item?.fileName }}
                  </div>
                </div>
              </div>
            </template>
            <template v-else>--</template>
          </template>
        </el-table-column>
        <el-table-column prop="inspectTime" label="检查时间"> </el-table-column>
        <el-table-column prop="recOpinions" label="整改意见"> </el-table-column>
        <el-table-column label="整改反馈">
          <template #default="{ row }">
            <el-input v-model="row.recFeedbackDesc"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="附件">
          <template #default="{ row }">
            <!-- class="upload-demo" -->
            <el-upload
              :action="uploadUrl"
              :headers="uploadHeaders"
              :accept="acceptTypes"
              name="uploadFile"
              :on-change="handleChange"
              :on-remove="handleRemove"
              :on-error="handleError"
              :on-success="handleSuccess"
              :on-preview="handlePreview"
              :show-file-list="false"
            >
              <el-button size="small" type="text" @click="handleUpload(row.id)"
                >点击上传</el-button
              >
            </el-upload>
            <div
              v-for="item in row.recFeedbackAttachmentArr"
              :key="item?.uuidFile"
            >
              <div class="file-item">
                <div
                  class="file-item--left"
                  @click.prevent="handleDownload2(item)"
                  :title="item.fileName"
                >
                  <i class="el-icon-folder"></i>{{ item?.fileName }}
                </div>
                <div
                  class="file-item--right"
                  @click="handleDelete2(item, row.id)"
                >
                  删除
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <p class="divider"><span class="required">*</span>整改反馈：</p>
    <el-form
      :model="formData"
      ref="formRef"
      class="form__content"
      :rules="formRules"
    >
      <el-form-item label="" prop="recFeedback">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入内容"
          v-model="formData.recFeedback"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="content-footer">
      <el-button type="primary" @click="handleSave">保 存</el-button>
      <el-button type="primary" @click="handleSubmit">提 交</el-button>
    </div>

    <el-dialog
      title="质量检查"
      v-model="commitVisible"
      destroy-on-close
      width="600px"
    >
      <div class="dialog__content">
        <!-- <div class="dialog__content--title">任务基本信息:</div> -->
        <div style="width: 100%; text-align: center; padding: 20px 0">
          是否确定提交？
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="commitVisible = false">取消</el-button>
          <!-- <el-button type="primary" @click="handleRequest">确认</el-button> -->
          <ReButton type="primary" debounce auto-loading @click="handleRequest"
            >确认</ReButton
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  reactive,
  ref,
  watch,
  defineProps,
  onMounted,
  nextTick,
  computed
} from "vue";
import { useRouter, useRoute } from "vue-router";

import { storageLocal } from "/@/utils/storage";
import { download } from "/@/utils/download";
import NotifMessage from "/@/utils/message/notification";
import { postFlowSubmit } from "/@/api/quality";
import { postGetStorageTmpData, postStorageTmpData } from "/@/api/acceptance";

import { acceptTypes, uploadUrl } from "../../types";
import { handleError, handlePreview } from "../../utils";

import ReButton from "/@/components/ReButton/index.vue";

const uploadHeaders = {
  Authorization: storageLocal.getItem("info")?.accessToken
};

const props = defineProps({
  checkContentList: {
    type: Array,
    default: () => []
  },
  taskId: {
    type: String,
    default: ""
  },
  storageData: {
    type: Object,
    default: () => {}
  },
  projectTeam: {
    type: Array,
    default: () => []
  }
});

const formRef = ref<HTMLFormElement | null>(null) as any;
let formData = reactive({
  insContentList: [],
  recOpinions: "",
  recFeedback: ""
});

// let currentTeam = reactive({
//   userName: "",
//   userId: ""
// }); // 下一节点的处理人信息

let commitVisible = ref(false);
const router = useRouter();
const route = useRoute();
// let spanArr = ref([]); // 用于存放每一行记录的合并数
// let pos = ref(null); // 用于存放每一行记录的合并数
// let unqualifiedForm = reactive({
//   unqualifiedList: [],
//   updateOpinion: ""
// });

let outterId = ref("");
let effective = ref("");

let cacheCurrentUser = ref(""); // 流程发起人的id

watch(
  () => props.checkContentList,
  newVal => {
    if (newVal && newVal.length > 0) {
      console.log(newVal);
      formData.insContentList = JSON.parse(JSON.stringify(newVal));
      formData.insContentList.forEach(item => {
        if (
          !item.insContentAttachmentArr ||
          !item.insContentAttachmentArr.length
        ) {
          item.insContentAttachmentArr = [];
        }
        if (
          !item.recFeedbackAttachmentArr ||
          !item.recFeedbackAttachmentArr.length
        ) {
          item.recFeedbackAttachmentArr = [];
        }
        item.recFeedbackDesc = "";
        item.recFeedbackAttachmentArr = [];
        if (item.isQualifiedCheck === "1") {
          item.isQualifiedRec = "1";
        } else {
          item.isQualifiedRec = "0";
        }
      });

      nextTick(() => {
        // getSpanArr(formData.insContentList);
        getStorageTmpData();
      });
    }
  },
  {
    deep: true,
    immediate: true
  }
);

watch(
  () => props.storageData,
  newVal => {
    if (newVal.inspectName) {
      console.log(newVal);
      formData.recOpinions = JSON.parse(
        JSON.stringify(props.storageData.recOpinions)
      );
      formData.recFeedback = JSON.parse(
        JSON.stringify(props.storageData.recFeedback)
      );
      // 流程发起人Id
      cacheCurrentUser.value = JSON.parse(
        JSON.stringify(props.storageData.inspectorId)
      );
    }
  },
  {
    deep: true,
    immediate: true
  }
);

const formRules = {
  recFeedback: { required: true, message: "请填写意见", trigger: "change" }
};

const filterFormData = list => {
  return list.filter(item => {
    return item.isQualifiedCheck === "0";
  });
};

const isError = computed(() => {
  const errList = formData.insContentList.filter(item => {
    return item.isQualifiedCheck === "0";
  });
  if (errList.length > 0) {
    return true;
  } else {
    return false;
  }
});

// 文件上传
let cacheTableItem = ref(0);

const handleUpload = index => {
  // console.log(index, "222");
  // 存储的是数据id
  cacheTableItem.value = index;
};

const handleRemove = (file, fileList) => {
  // defaultFileList.value = fileList;
  console.log(file, fileList);
};

const handleChange = (file, fileList) => {
  console.log(file, fileList);
};

const handleSuccess = file => {
  if (file.code === 200) {
    let cacheIndex = null;
    formData.insContentList.forEach((item, index) => {
      if (item.id === cacheTableItem.value) {
        cacheIndex = index;
      }
    });
    console.log(cacheIndex, "cacheIndex");
    formData.insContentList[cacheIndex].recFeedbackAttachmentArr.push(
      file.data
    );
    // console.log(formData.insContentList, "formData.insContentList");
    // file.data;
  }
};

// table 处理相关--------------------------------------
// const getSpanArr = data => {
//   // data就是我们从后台拿到的数据
//   for (let i = 0; i < data.length; i++) {
//     if (i === 0) {
//       spanArr.value.push(1);
//       pos.value = 0;
//     } else {
//       // 判断当前元素与上一个元素是否相同
//       if (data[i].content === data[i - 1].content) {
//         spanArr.value[pos.value] += 1;
//         spanArr.value.push(0);
//       } else {
//         spanArr.value.push(1);
//         pos.value = i;
//       }
//     }
//   }
// };
// const objectSpanMethod = ({ rowIndex, columnIndex }) => {
//   if (columnIndex === 1) {
//     const _row = spanArr.value[rowIndex];
//     const _col = _row > 0 ? 1 : 0;
//     // console.log(`rowspan:${_row} colspan:${_col}`);
//     return {
//       // [0,0] 表示这一行不显示， [2,1]表示行的合并数
//       rowspan: _row,
//       colspan: _col
//     };
//   }
// };
const handleBack = () => {
  // TODO  根据来源进行处理
  if (route.query.source === "work") {
    router.push({ path: "/work/dashboard", replace: true });
  } else {
    router.push({ path: "/quality/inspection", replace: true });
  }
};

const handleSubmit = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  commitVisible.value = true;
};

const handleRequest = async done => {
  try {
    const { instanceId, nodeDefId, flowId, contractId } = route.query;
    const info = storageLocal.getItem("info");
    const params = {
      formBaseInfo: {
        id: contractId,
        ...formData
      },
      formSubMap: {
        flowType: 11,
        nodeId: nodeDefId,
        isRectification: "",
        recheckPass: "",
        isChargehand: "",
        flowId,
        procInstId: instanceId,
        taskId: props.taskId,
        opinion: `整改反馈：${formData.recFeedback}`,
        assignee: cacheCurrentUser.value
      },
      tmpStorage: {
        nodeId: nodeDefId,
        flowId,
        taskId: props.taskId,
        handlerId: info?.userId ?? "",
        userId: info?.userId ?? "",
        valueJson: JSON.stringify({
          ...formData,
          flowInfoId: flowId
        })
      }
    };

    // 根据后端要求。传一个outterId
    if (outterId.value) {
      const joinData = Object.assign(params.tmpStorage, {
        outterId: outterId.value
      });
      params.tmpStorage = joinData;
    }
    // 根据后端要求。传一个effective
    if (effective.value) {
      const joinData = Object.assign(params.tmpStorage, {
        effective: effective.value
      });
      params.tmpStorage = joinData;
    }

    const { code, data } = await postFlowSubmit(params);
    console.log(code, data);
    if (code === 200) {
      NotifMessage.success("提交成功");
      handleBack();
    }
  } catch (err) {
    console.log(err);
  } finally {
    setTimeout(() => {
      done();
    }, 1000);
  }
};

const handleSave = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  const info = storageLocal.getItem("info");
  const { flowId, nodeDefId } = route.query;
  let params = {
    nodeId: nodeDefId,
    taskId: props.taskId,
    flowId,
    handlerId: info ? info?.userId : "",
    valueJson: JSON.stringify(formData)
  };

  if (outterId.value) {
    params = Object.assign(params, { outterId: outterId.value });
  }

  if (effective.value) {
    params = Object.assign(params, { effective: effective.value });
  }

  try {
    const { code, message } = await postStorageTmpData(params);
    if (code === 200) {
      NotifMessage.success("保存成功");
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

const getStorageTmpData = async () => {
  const info = storageLocal.getItem("info");
  const { flowId, nodeDefId } = route.query;
  let params = {
    nodeId: nodeDefId,
    taskId: props.taskId,
    flowId,
    handlerId: info ? info?.userId : ""
  };

  const { code, data } = await postGetStorageTmpData(params);
  if (code === 200) {
    if (data?.valueJson) {
      const { insContentList, recOpinions, recFeedback } = JSON.parse(
        data.valueJson
      );

      formData.insContentList = JSON.parse(JSON.stringify(insContentList));
      formData.insContentList.forEach(item => {
        if (
          !item.insContentAttachmentArr ||
          !item.insContentAttachmentArr.length
        ) {
          item.insContentAttachmentArr = [];
        }
      });
      formData.insContentList.forEach(item => {
        if (
          !item.recFeedbackAttachmentArr ||
          !item.recFeedbackAttachmentArr.length
        ) {
          item.recFeedbackAttachmentArr = [];
        }
      });

      formData.recOpinions = JSON.parse(JSON.stringify(recOpinions));
      formData.recFeedback = JSON.parse(JSON.stringify(recFeedback));

      outterId.value = data.outterId;
      effective.value = data?.effective ?? "";
    }
  }
  // nextTick(() => {
  //   getSpanArr(formData.insContentList);
  // });
};

// const handleDownload = item => {
//   if (!item) return;
//   download(item);
// };

// const handleDelete = (item, index) => {
//   formData.insContentList[index].insContentAttachmentArr =
//     formData.insContentList[index].insContentAttachmentArr.filter(i => {
//       return item.uuidFile !== i.uuidFile;
//     });
// };

const handleDownload2 = item => {
  if (!item) return;
  download(item);
};

const handleDelete2 = (item, indexId) => {
  let cacheIndex = null;
  formData.insContentList.forEach((item, index) => {
    if (item.id === indexId) {
      cacheIndex = index;
    }
  });
  formData.insContentList[cacheIndex].recFeedbackAttachmentArr =
    formData.insContentList[cacheIndex].recFeedbackAttachmentArr.filter(i => {
      return item.uuidFile !== i.uuidFile;
    });
};

onMounted(() => {
  nextTick(() => {
    // getStorageTmpData();
  });
});
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  &-table {
    margin-bottom: 20px;
    p {
      padding: 10px 0;
    }
  }
  &-footer {
    margin-top: 20px;
    width: inherit;
    height: 40px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}
.divider {
  margin-bottom: 10px;
  // border-left: 3px solid #409eff;
  text-indent: 8px;
  .required {
    color: rgb(245, 108, 108);
    margin-right: 4px;
  }
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  &--left {
    flex: 1;
    margin-right: 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    .el-icon-folder {
      margin-right: 5px;
    }
    &:hover {
      cursor: pointer;
      color: #409eff;
    }
  }
  &--right {
    font-size: 10px;
    width: 40px;
    text-align: center;
    color: red;
  }
}
</style>
